//
// Created by 城门虾米 on 2019/11/15.
// Copyright (c) 2019 lijunge. All rights reserved.
//

#import "PIFinger.h"
#define MAX_FINGER_INDEX 24
@implementation PIFinger {
    NSMutableDictionary *_fingerIndex;
    int _indexes[MAX_FINGER_INDEX];
}

- (instancetype) init {
    if (self == [super init]) {
        _fingerIndex = [NSMutableDictionary new];
        memset(_indexes, 0, sizeof(_indexes));
    }
    return self;
}

+ (instancetype)shared {
    static PIFinger *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [PIFinger new];
    });
    return instance;
}

- (int)findIndex {

    int index = -1;
    for (int i = 0; i < MAX_FINGER_INDEX; ++i) {
        if (_indexes[i] == 0) {
            _indexes[i] = 1;
            index = i;
            break;
        }
    }
    return index;
}

- (int)getIndexWithFingerPointString:(NSString *)touchString phase:(TouchPhase)phase {
    
    if (phase == TouchPhaseEnded || phase == TouchPhaseCancled) {
        NSNumber *indexObj = [_fingerIndex objectForKey:touchString];
        if (indexObj != nil) {
            int index = [indexObj intValue];
            [_fingerIndex removeObjectForKey:touchString];
            _indexes[index] = 0;
            return index;
        }
        return -1;
    }

    NSNumber *indexObj = [_fingerIndex objectForKey:touchString];
    if (indexObj != nil) {
        return [indexObj intValue];
    }

    if (phase == TouchPhaseBegan) {
        int index = [self findIndex];
        if (index != -1) {
            [_fingerIndex setValue:[NSNumber numberWithInt:index] forKey:touchString];
        }
        return index;
    }
    return -1;
}

@end
